package com.malljelly.study.config;


import com.malljelly.study.authentication.ImoocAuthenctiationFailureHandler;
import com.malljelly.study.authentication.ImoocAuthenticationSuccessHandler;
import com.malljelly.study.properties.SecurityProperties;
import com.malljelly.study.validate.code.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created by 骑着蜗牛去旅行 on 2018/8/18.
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ImoocAuthenticationSuccessHandler imoocAuthenticationSuccessHandler;


    @Autowired
    private ImoocAuthenctiationFailureHandler imoocAuthenctiationFailureHandler;

    /**
     * Security 加密用的,可以自定义实现PasswordEncoder 如base64 md5+盐
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
         return new BCryptPasswordEncoder();
    }


    @Override
    protected  void  configure(HttpSecurity http) throws Exception {

//        http.formLogin()                    //  定义当需要用户登录时候，转到的登录页面。
//                .and()
//                .authorizeRequests()        // 定义哪些URL需要被保护、哪些不需要被保护
//                .anyRequest()               // 任何请求,登录后可以访问
//                .authenticated();           //身份认证
        ValidateCodeFilter validateCodeFilter=new ValidateCodeFilter();
        validateCodeFilter.setAuthenticationFailureHandler(imoocAuthenctiationFailureHandler);
        validateCodeFilter.setSecurityProperties(securityProperties);
        validateCodeFilter.afterPropertiesSet();





        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)//加入自定义过滤器
                .formLogin()
                .loginPage("/authentication/require") //跳自定义controller
                .loginProcessingUrl("/authentication/form") //等于表单提交路径
                .successHandler(imoocAuthenticationSuccessHandler)//表单登录提交成功以后返回的json
                .failureHandler(imoocAuthenctiationFailureHandler)//表单登录提交失败以后返回的json
                .and()
                .authorizeRequests()  //对请求授权
                .antMatchers("/authentication/require",securityProperties.getBrowser().getLoginPage(),"/code/image").permitAll() //访问登录页不需要身份认证
                .anyRequest() //任何请求
                .authenticated() //身份认证
                .and()
                .csrf().disable(); //csrf关闭
    }
}
